package com.iqilu.ksd.activity.live;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.iqilu.ksd.R;
import com.iqilu.ksd.activity.BaseActivity;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.constant.ImageSize;
import com.iqilu.ksd.utils.CacheUtils;
import com.iqilu.ksd.widget.LigDialog;
import com.muzhi.camerasdk.model.CameraSdkParameterInfo;
import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import id.zelory.compressor.Compressor;
import okhttp3.Response;

/**
 * Created by Coofee on 2016/11/24.
 */

public class PhotoActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "PhotoActivity";

    private int id;
    private MyAdapter adapter;
    private String pics[] = new String[4];

    private ProgressDialog progressDialog;
    private CameraSdkParameterInfo mCameraSdkParameterInfo = new CameraSdkParameterInfo();

    private Button btCancel;
    private Button btSend;
    private EditText etEmoji;
    private RelativeLayout layPic;
    private GridView gvImg;

    private LigDialog ligDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_live_view_common);
        initView();
        layPic.setVisibility(View.VISIBLE);
        Intent mIntent = getIntent();
        id = mIntent.getIntExtra("id", 0);
        if (!TextUtils.isEmpty(mIntent.getStringExtra("photoPath"))) {
            pics[0] = mIntent.getStringExtra("photoPath");
            Log.i(TAG, "photoPath=" + pics[0]);
//            new CompressThread().execute();
        } else {
            Bundle bundle = mIntent.getExtras();
            if (bundle != null) {
                mCameraSdkParameterInfo = (CameraSdkParameterInfo) bundle.getSerializable(CameraSdkParameterInfo.EXTRA_PARAMETER);
                ArrayList<String> list = mCameraSdkParameterInfo.getImage_list();
                if (list != null) {
                    Log.i(TAG, "list.size=" + list.size());
                    for (int i = 0; i < list.size(); i++) {
                        pics[i] = list.get(i);
                    }
                }
            }
        }
        gvImg.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 3 && TextUtils.isEmpty(pics[3])) {
                    int j = 0;
                    for (int i = 0; i < 4; i++) {
                        if (TextUtils.isEmpty(pics[i])) {
                            j = i;
                            break;
                        }
                    }
                    j = 4 - j;
                    Log.i(TAG, "j=" + j);
                    initAlbumConfig(j);
                    Intent intent = new Intent();
                    intent.setClassName(getApplication(), "com.muzhi.camerasdk.PhotoPickActivity");
                    Bundle b = new Bundle();
                    b.putSerializable(CameraSdkParameterInfo.EXTRA_PARAMETER, mCameraSdkParameterInfo);
                    intent.putExtras(b);
                    startActivityForResult(intent, CameraSdkParameterInfo.TAKE_PICTURE_FROM_GALLERY);
                }
            }
        });
        new CompressThread().execute();
//        new CompressImage(0).execute();
    }

    private void initView() {
        btCancel = getView(R.id.bt_cancel);
        btSend = getView(R.id.bt_send);
        etEmoji = getView(R.id.et_emoji);
        layPic = getView(R.id.lay_pic);
        gvImg = getView(R.id.gv_img);
        btCancel.setOnClickListener(this);
        btSend.setOnClickListener(this);
    }

    private void initAlbumConfig(int max_img) {
        mCameraSdkParameterInfo.setSingle_mode(false);
        mCameraSdkParameterInfo.setShow_camera(false);
        mCameraSdkParameterInfo.setCroper_image(false);
        mCameraSdkParameterInfo.setFilter_image(false);
        mCameraSdkParameterInfo.setMax_image(max_img);
    }

    private void toSend() {
        boolean isEmpty = true;
        for (int i = 0; i < pics.length; i++) {
            if (TextUtils.isEmpty(pics[i])) break;
            isEmpty = false;
        }
        if (isEmpty) {
            Toast.makeText(this, R.string.live_upload_image_empty, Toast.LENGTH_SHORT).show();
        } else {
            new UploadImage(etEmoji.getText().toString()).execute();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CameraSdkParameterInfo.TAKE_PICTURE_FROM_GALLERY) {
            if (data == null) return;
            mCameraSdkParameterInfo = (CameraSdkParameterInfo) data.getExtras().getSerializable(CameraSdkParameterInfo.EXTRA_PARAMETER);
            ArrayList<String> list = mCameraSdkParameterInfo.getImage_list();
            if (list == null || list.size() == 0) return;
            int j = 0;
            for (int i = 0; i < pics.length; i++) {
                if (TextUtils.isEmpty(pics[i]) && j < list.size()) {
                    pics[i] = list.get(j);
                    j++;
                }
            }
            new CompressThread().execute();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_cancel:
                finish();
                break;
            case R.id.bt_send:
                toSend();
                break;
            default:
                break;
        }
    }

    class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return pics.length;
        }

        @Override
        public Object getItem(int position) {
            return pics[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(PhotoActivity.this).inflate(R.layout.list_item_live_photo, null);
                holder.imgThumb = (SimpleDraweeView) convertView.findViewById(R.id.img_thumb);
                holder.imgDel = (ImageView) convertView.findViewById(R.id.img_del);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            if (!TextUtils.isEmpty(pics[position])) {
                holder.imgThumb.setImageURI(Uri.parse("file://" + pics[position]));
                holder.imgDel.setVisibility(View.VISIBLE);
            } else {
                holder.imgDel.setVisibility(View.GONE);
                holder.imgThumb.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                if (position == 3) {
                    holder.imgThumb.setImageURI(Uri.parse("res://" + getPackageName() + "/" + R.drawable.bg_live_addphoto));
                } else {
                    holder.imgThumb.setImageURI(Uri.parse("res://" + getPackageName() + "/" + R.drawable.bg_live_photoframe));
                }
            }

            holder.imgDel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pics[position] = "";
                    String newPics[] = new String[4];
                    int i = 0;
                    for (int j = 0; j < pics.length; j++) {
                        if (!TextUtils.isEmpty(pics[j])) {
                            newPics[i] = pics[j];
                            i++;
                        }
                    }
                    pics = newPics;
                    adapter.notifyDataSetChanged();
                }
            });
            return convertView;
        }

        class ViewHolder {
            SimpleDraweeView imgThumb;
            ImageView imgDel;
        }
    }

    class UploadImage extends AsyncTask<Void, Void, Void> {

        int result = 0;
        String description;
        Map<String, File> files = new HashMap<>();

        public UploadImage(String description) {
            this.description = Uri.encode(description);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = ProgressDialog.show(PhotoActivity.this, "", getResources().getString(R.string.live_upload_image), true, false);
        }

        @Override
        protected Void doInBackground(Void... params) {
            for (int i = 0; i < pics.length; i++) {
                if (TextUtils.isEmpty(pics[i])) break;
                File file = new File(pics[i]);
                files.put(file.getName(), file);
            }
            Response response = null;
            String url = Api.URL_LIVE_IMAGE;
            try {
                response = OkHttpUtils.post().url(url).addParams("liveid", "" + id).addParams("description", "" + description).files("filedata[]", files).tag(this).build().execute();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (response != null) {
                try {
                    Log.i(TAG,"response====>"+response.body().string());
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    result = jsonObject.getInt("status");
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            progressDialog.dismiss();
            if (result == 1) {
                Toast.makeText(PhotoActivity.this, R.string.live_addvideo_success, Toast.LENGTH_SHORT).show();
                finish();
            } else {
                Toast.makeText(PhotoActivity.this, R.string.live_addvideo_fail, Toast.LENGTH_SHORT).show();
            }
        }

    }

    class CompressThread extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            ligDialog = new LigDialog(PhotoActivity.this, getString(R.string.waiting));
            ligDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            for (int i = 0; i < pics.length; i++) {
                if (TextUtils.isEmpty(pics[i]) || pics[i].contains("compress")) continue;
                Log.i(TAG,"pics[i]="+pics[i]);
                File compressedImage = new Compressor.Builder(PhotoActivity.this)
                        .setMaxWidth(ImageSize.MIDDLE_WIDTH)
                        .setMaxHeight(ImageSize.MIDDLE_HEIGHT)
                        .setQuality(90)
                        .setCompressFormat(Bitmap.CompressFormat.JPEG)
                        .setDestinationDirectoryPath(CacheUtils.getCompressDir(PhotoActivity.this))
                        .build()
                        .compressToFile(new File(pics[i]));
                pics[i] = compressedImage.getPath();
                compressedImage = null;
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            ligDialog.dismiss();
            if (adapter == null) {
                adapter = new MyAdapter();
                gvImg.setAdapter(adapter);
            }
            adapter.notifyDataSetChanged();
        }

    }
}
